package com.app.demo;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.app.demo.activity.BaseActivity;
import com.app.demo.base.EventMsg;
import com.app.demo.base.RxBus;
import com.app.demo.base.TitleViews;
import com.app.demo.imageEdit.ImageEditActivity;
import com.app.demo.selectimage.SelectImageActivity;
import com.app.demo.util.ImageUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

public class MainActivity extends BaseActivity {
    private Uri photoURI;

    private String url;
    //照片存储路径
    private String mCurrentPhotoPath = "";
    //照片名称
    private String mCurrentPhotoName = "";
    private static String mDir = "";
    @SuppressLint("CheckResult")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getpermissions();
        // Example of a call to a native method

        ImageView a = findViewById(R.id.image);
        String imageUri = "drawable://" + R.drawable.ic_launcher_background;
        ImageLoader.getInstance().displayImage(imageUri, a);
        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dispatchTakePictureIntent();
            }
        });
        setOnClickListener(R.id.button, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SelectImageActivity.class);
                startActivity(intent);

            }
        });

        setOnClickListener(R.id.button_filter, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (url != null) {
                    String temp = url;
                    if (url.startsWith("file://")) {
                        temp = url.substring(7);
                    }
                    ImageEditActivity.startPostImageEditActivity(MainActivity.this, temp);
                }
            }
        });

        RxBus.getInstance().toObservable().map(new Function<Object, EventMsg>() {
            @Override
            public EventMsg apply(Object o) throws Exception {
                return (EventMsg) o;
            }
        }).subscribe(new Consumer<EventMsg>() {
            @Override
            public void accept(EventMsg eventMsg) throws Exception {
                if (eventMsg != null) {
                    ImageView imageView = getView(R.id.image);
                    switch (eventMsg.code) {
                        case EventMsg.CODE_RESULT_SELECT_IMAGE:
                            url = eventMsg.msg;
                            if (!eventMsg.msg.startsWith("file://")) {
                                url = "file://" + url;
                            }
                            ImageLoader.getInstance().displayImage(eventMsg.msg, imageView, ImageUtil.getOptions());
                            break;
                        case EventMsg.CODE_RESULT_FILTE_IMAGE:
                            url = eventMsg.msg;
                            if (!eventMsg.msg.startsWith("file://")) {
                                url = "file://" + url;
                            }
                            ImageLoader.getInstance().displayImage(url, imageView, ImageUtil.getOptions());
                    }
                }
            }
        });

    }
    private void getpermissions() {
        if (!AndPermission.hasPermissions(this, CAMERA_SERVICE))
            AndPermission.with(this)
                    .runtime()
                    .permission(
                            Permission.Group.STORAGE,
                            Permission.Group.CAMERA
                    ).start();
    }
    @Override
    protected void initTitle(TitleViews titleViews) {
        titleViews.left_container.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleViews.left_container_left_image.setVisibility(View.VISIBLE);
        titleViews.left_container_left_image.setBackgroundResource(R.drawable.left_gray);
        titleViews.center_container_title_text.setText("首页入口");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK){
            ImageView imageView = getView(R.id.image);
            Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
            imageView.setImageBitmap(bitmap);
            url = mCurrentPhotoPath;

        }

    }
    private void dispatchTakePictureIntent() {
        // 创建启动相机的Intent
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // 创建保存图片的File对象
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // 出现异常
                ex.printStackTrace();
            }
            if (photoFile != null) {
                // 将File对象转换为Uri对象，以便在Intent中传递
                Uri photoUri = FileProvider.getUriForFile(this,
                        "com.app.demo.fileprovider",
                        photoFile);
                // 将Uri对象添加到Intent中
                photoURI = photoUri;
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                // 启动相机
                startActivityForResult(takePictureIntent, 1);
            }
        }
    }
    //创建

    // 创建一个文件来保存图片
    private File createImageFile() throws IOException {
        // 创建一个以当前时间命名的图片文件
//        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        long timestamp = System.currentTimeMillis();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String timeStamp = dateFormat.format(new Date(timestamp));
        String imageFileName = "JPEG_" + timeStamp + "_.jpg";
        File storageDir;

        if("".equals(mDir)){
            storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
//            storageDir = imgDirectory;
            if (!storageDir.exists()) {
                storageDir.mkdirs();
            }
        }else{
            storageDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES)+"/"+mDir);
//            storageDir = new File(imgDirectory+"/"+mDir);
            if (!storageDir.exists()) {
                storageDir.mkdirs();
            }
        }
        // 创建图片文件
//        File imageFile = File.createTempFile(
//                imageFileName,  /* prefix */
//                ".jpg",         /* suffix */
//                storageDir      /* directory */
//        );
        File imageFile = new File(storageDir, imageFileName);
        try {
            imageFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 保存图片文件路径
        mCurrentPhotoPath = imageFile.getAbsolutePath();
        //保存文件名称
        mCurrentPhotoName = imageFile.getName();
        return imageFile;
    }
}
